package com.android.fragmentdemo.thread14

import org.junit.Test
import java.util.concurrent.locks.ReentrantLock

class Demo14 {
    @Test
    fun testRunnable() {

        val lock1 = ReentrantLock()
        val lock2 = ReentrantLock()

        val thread1 = Thread(ThreadTest(lock1, lock2), "thread1")
        val thread2 = Thread(ThreadTest(lock2, lock1), "thread2")

        thread1.start()
        thread2.start()

        Thread.sleep(5 * 1000)
    }

    class ThreadTest(lock1: ReentrantLock, lock2: ReentrantLock) : Runnable {
        private val mLock1 = lock1
        private val mLock2 = lock2
        override fun run() {
            try {
                while (!mLock1.tryLock()) {
                    Thread.sleep(500)
                    println("${Thread.currentThread().name}---尝试获取锁")
                }

                while (!mLock2.tryLock()) {
                    Thread.sleep(500)
                    println("${Thread.currentThread().name}---尝试获取锁")
                }
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            } finally {
                mLock1.unlock()
                mLock2.unlock()
                println("${Thread.currentThread().name}---获取到了锁")
            }
        }
    }

}